package com.ultimate.management.filter;

import com.alibaba.fastjson.JSON;
import com.ultimate.management.entity.LoginUser;
import com.ultimate.management.util.response.JwtUtil;
import com.ultimate.management.util.response.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token，指定你要获取的请求头叫什么
        String token = request.getHeader("token");
        logger.info("当前Url::"+request.getRequestURL()+"获取Token--------->"+token);

        if(!StringUtils.hasText(token) || "undefined".equalsIgnoreCase(token.trim())){
            //不需要token的路由可以直接放行
            filterChain.doFilter(request,response);
            return;
        }

        //解析出userId
        Claims claims = null;
        try{
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            throw new RuntimeException("token非法");
        }

        //从redis中获取用户信息
        String userId = claims.getSubject();
        //
        Object userJsonStr = redisCache.getCacheObject("manager:" + userId);
        LoginUser loginUser = JSON.parseObject(String.valueOf(userJsonStr),LoginUser.class);

        //判断获取到用户信息是否为空
        //可能redis缓存会过期
        if(Objects.isNull(loginUser)){
            //抛出一个异常
            throw new RuntimeException("用户未登录");
        }

        //把最终的LoginUser用户信息存入上下文
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request, response);

    }
}
